<template>
  <div class="construction-log" @scroll="loadMoreData" v-loading="isLoadingLog">
    <template v-if="logList.length">
      <div class="time-line">
        <el-timeline :reverse="true">
          <el-timeline-item v-for="(item, index) in logList" :key="index" color="#2991FF" size="large" :hollow="true">
            <div class="time">
              <div>
                <span class="year">{{ date(item.submitTime).value }}</span>
              </div>
              <div class="day">
                <el-icon><Clock /></el-icon>
                <span>{{ time(item.submitTime).value }}</span>
              </div>
            </div>
            <div class="ml10">
              <div class="list-title">
                <div class="list-title-user">
                  <CustomAvatar :info="item" avatarName="submitUserName" :avatarStyle="avatarStyle" />
                  <span class="list-title-name">{{ item.submitUserName }}</span>
                  <el-divider direction="vertical" />
                  <span class="list-title-role">{{ item.submitUserRoleNames }}</span>
                </div>
                <el-button type="primary" link @click="handelDelLog(item.logId)">删除</el-button>
              </div>
              <div class="list-desc">
                <div class="list-desc-content">{{ item.logDesc }}</div>
                <div class="list-desc-images">
                  <el-image
                    :preview-src-list="item.picList"
                    v-for="imgItem in item.picList"
                    :key="imgItem"
                    :src="imgItem"
                  ></el-image>
                  <div class="video-box" v-for="videoItem in item.videoList" :key="videoItem">
                    <svg-icon iconClass="play-icon" color="#fff" @click="handelPreviewVideo(videoItem)" />
                    <video :src="videoItem"></video>
                  </div>
                </div>
                <div class="list-desc-name"></div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <el-divider>已经到底了</el-divider>
      <div style="height: 64px"></div>
    </template>
    <el-empty v-else />

    <!--  预览视频 start  -->
    <div class="preview-dialog">
      <el-dialog title="视频预览" v-model="isVideoPreview" @close="handelClosePreviewVideo">
        <video v-if="isVideoPreview" :src="previewVideoUrl" controls></video>
      </el-dialog>
    </div>
    <!--    预览视频 end-->

    <!-- 新建日志 start -->
    <div
      class="add-construction-log"
      :style="{ width: !collapsed ? '100%' : 'calc(100% - 200px)', left: !collapsed ? '0' : '200px' }"
    >
      <el-button type="primary" @click="handelAddLog">新建日志</el-button>
      <el-dialog v-model="isShowLogDialog" width="556" :show-close="false" @close="handelLogCancel">
        <el-form
          :model="logForm"
          :rules="logFormRules"
          label-width="auto"
          ref="logFormRef"
          v-if="isShowLogDialog"
          v-loading="isLoadingLog"
          element-loading-text="数据提交中..."
        >
          <el-form-item label="业主可见" prop="isVisible">
            <el-radio-group v-model="logForm.isVisible">
              <el-radio :value="1" size="large">是</el-radio>
              <el-radio :value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="汇报内容" prop="logDesc">
            <el-input v-model="logForm.logDesc" type="textarea" placeholder="请输入" :maxlength="80" :autosize="{ minRows: 3 }" />
          </el-form-item>
          <el-form-item label="上传图片">
            <image-video-upload
              :file-list="picData"
              tip="只能上传jpg/png，且不超过10M,最大支持上传9张"
              accept=".jpg,.png"
              multiple
              :max-size="10"
              :max-length="9"
              @upload-success="uploadImage"
              @upload-remove="uploadImageRemove"
            />
          </el-form-item>
          <el-form-item label="上传视频">
            <image-video-upload
              :file-list="videoData"
              fileType="video"
              isLimitDuration
              accept=".avi,.mov,.mp4,.wmv"
              tip="限制视频时长不超过60秒，最多支持6个视频"
              multiple
              :max-size="200"
              :max-length="6"
              @upload-success="uploadVideo"
              @upload-remove="uploadVideoRemove"
            />
          </el-form-item>
        </el-form>
        <template #header>
          <title-view title="新建日志"></title-view>
        </template>
        <template #footer>
          <div class="dialog-footer">
            <el-button style="width: 92px; background-color: #f2f3f5; border: 0" @click="handelLogCancel">取消</el-button>
            <el-button style="width: 92px; margin-left: 0" type="primary" @click="handelLogConfirm"> 保存 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 新建日志  end-->
  </div>
</template>

<script setup>
/**
 * TODO:整改和施工日志，时间线组件相同，后续优化可封装
 *  TODO：时间线组件和全局组件TimeLine组件可合并，并封装为通用全局组件
 */
import { getCurrentInstance, nextTick, ref } from "vue";
import { dayjs } from "element-plus";
import { Clock } from "@element-plus/icons-vue";
import CustomAvatar from "@/components/AvatarView/index.vue";
import useComputedParams from "@/hooks/useComputedParams";
import { constructionLog, addCustomerLog, delCustomerLog } from "@/apis/constructionLog";
import useReceiveMainData from "@/hooks/microApp/useReceiveMainData";

const { proxy } = getCurrentInstance();
const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const { collapsed } = useReceiveMainData();

const avatarStyle = {
  width: "32px",
  height: "32px",
  borderRadius: "50%"
};

const isLoadingLog = ref(false);
const isMore = ref(true);
const params = ref({
  customerId: props.customerId,
  current: 1,
  size: 10
});
const logList = ref([]);
const date = useComputedParams(time => {
  return dayjs(time).format("YYYY-MM-DD");
});
const time = useComputedParams(time => {
  return dayjs(time).format("HH:mm:ss");
});
const getConstructionLog = async () => {
  try {
    isLoadingLog.value = true;
    const { data } = await constructionLog(params.value);
    const reqData =
      data?.list?.map(item => {
        return {
          ...item,
          picList: item.picUrls ? item.picUrls?.split(",") : [],
          videoList: item.videoUrls ? item.videoUrls?.split(",") : []
        };
      }) || [];
    logList.value = [...logList.value, ...reqData];
    isMore.value = logList.value.length === data.total;
    isLoadingLog.value = false;
  } catch (err) {
    isLoadingLog.value = false;
  }
};
const loadMoreData = e => {
  if (isMore.value) return;
  const { scrollTop, scrollHeight, clientHeight } = e.target;
  if (scrollTop + clientHeight >= scrollHeight) {
    params.value.current++;
    getConstructionLog();
  }
};

/**
 * 新增日志
 */
const isShowLogDialog = ref(false);
const isLoadingSubmitLog = ref(false);
const initLogForm = {
  customerId: "",
  isVisible: 1,
  logDesc: "",
  picUrls: "",
  picIds: "",
  videoIds: "",
  videoUrls: ""
};
const logFormRules = {
  isVisible: [
    {
      required: true,
      message: "请选择业主可见",
      trigger: "change"
    }
  ],
  logDesc: [
    {
      required: true,
      message: "请输入汇报内容",
      trigger: "blur"
    }
  ]
};
const logForm = ref({
  ...initLogForm
});
const picData = ref([]);
const videoData = ref([]);
const handelAddLog = () => {
  isShowLogDialog.value = true;
};
const uploadImage = data => {
  picData.value.push({
    ...data
  });
};
const uploadImageRemove = index => {
  picData.value.splice(index, 1);
};
const uploadVideo = data => {
  videoData.value.push({
    ...data
  });
};
const uploadVideoRemove = index => {
  videoData.value.splice(index, 1);
};
const handelLogConfirm = () => {
  proxy.$refs.logFormRef.validate(async valid => {
    if (!valid) return proxy.$modal.msgError("请完善信息");
    try {
      isLoadingSubmitLog.value = true;
      const postData = {
        ...logForm.value,
        customerId: props.customerId,
        picIds: picData.value.map(item => item.fileId).join(","),
        videoIds: videoData.value.map(item => item.fileId).join(","),
        picUrls: picData.value.map(item => item.fileUrl).join(","),
        videoUrls: videoData.value.map(item => item.fileUrl).join(",")
      };
      await addCustomerLog(postData);
      isLoadingSubmitLog.value = false;
      params.value.current = 1;
      logList.value = [];
      handelLogCancel();
      getConstructionLog();
      proxy.$modal.msgSuccess("新增成功");
    } catch (err) {
      isLoadingSubmitLog.value = false;
    }
  });
};
const handelLogCancel = async () => {
  await nextTick();
  proxy.$refs.logFormRef.resetFields();
  logForm.value = {
    ...initLogForm
  };
  picData.value = [];
  videoData.value = [];
  isShowLogDialog.value = false;
};

/**
 * 预览视频
 */
const isVideoPreview = ref(false);
const previewVideoUrl = ref("");
const handelPreviewVideo = url => {
  previewVideoUrl.value = url;
  isVideoPreview.value = true;
};
const handelClosePreviewVideo = () => {
  previewVideoUrl.value = "";
  isVideoPreview.value = false;
};

/**
 * 删除日志
 */
const handelDelLog = logId => {
  proxy.$modal.confirm("你确定删除该日志吗？").then(async () => {
    try {
      await delCustomerLog(logId);
      params.value.current = 1;
      logList.value = [];
      getConstructionLog();
      proxy.$modal.msgSuccess("删除成功");
    } catch (err) {
      proxy.$modal.msgError("删除失败");
    }
  });
};

getConstructionLog();
</script>

<style scoped lang="scss">
@use "constructionLog";

.preview-dialog {
  :deep(.el-dialog) {
    video {
      width: 100%;
      height: 50vh !important;
    }
  }
}
</style>
